import Parser = require('tree-sitter');

export class ASTHelper {
  // 查找指定位置的最小包含节点
  static findNodeAtPosition(
    node: Parser.SyntaxNode, 
    position: { row: number; column: number }
  ): Parser.SyntaxNode | null {
    if (!this.nodeContainsPosition(node, position)) {
      return null;
    }

    // 递归查找子节点中更精确的匹配
    for (let i = 0; i < node.namedChildCount; i++) {
      const child = node.namedChild(i);
      if (child) {
        const match = this.findNodeAtPosition(child, position);
        if (match) return match;
      }
    }

    return node;
  }

  // 查找语义上更有意义的节点
  static findSemanticNode(
    node: Parser.SyntaxNode,
    position: { row: number; column: number }
  ): Parser.SyntaxNode {
    let current = this.findNodeAtPosition(node, position);
    if (!current) return node;

    while (current) {
      // 字符串内部节点处理
      if (this.isStringNode(current.type)) {
        current = this.findStringParent(current);
      }
      
      // 如果已经是有意义的节点类型，直接返回
      if (this.isSemanticNode(current.type)) {
        return current;
      }
      
      current = current.parent as Parser.SyntaxNode;
    }
    
    return node;
  }

  // 检查节点是否包含指定位置
  static nodeContainsPosition(
    node: Parser.SyntaxNode, 
    position: { row: number; column: number }
  ): boolean {
    const start = node.startPosition;
    const end = node.endPosition;
    
    if (position.row < start.row || position.row > end.row) {
      return false;
    }
    
    if (position.row === start.row && position.column < start.column) {
      return false;
    }
    
    if (position.row === end.row && position.column > end.column) {
      return false;
    }
    
    return true;
  }

  // 检查是否为字符串相关节点
  private static isStringNode(type: string): boolean {
    return type === 'string_start' || 
           type === 'string_content' || 
           type === 'string_end';
  }

  // 检查是否为语义节点
  private static isSemanticNode(type: string): boolean {
    return type === 'call' || 
           type === 'function_call' || 
           type === 'identifier' ||
           type === 'attribute';
  }

  // 查找字符串的父节点
  private static findStringParent(node: Parser.SyntaxNode): Parser.SyntaxNode {
    let parent = node.parent;
    while (parent && parent.type !== 'call' && parent.type !== 'argument_list') {
      if (parent.type === 'string') {
        node = parent;
        break;
      }
      parent = parent.parent;
    }
    
    // 继续向上查找到函数调用
    if (parent && (parent.type === 'call' || parent.type === 'argument_list')) {
      return parent.type === 'argument_list' ? parent.parent || node : parent;
    }
    
    return node;
  }
}